import com.google.common.io.Files
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
//import java.io.File
import java.nio.charset.StandardCharsets;
import groovy.json.StringEscapeUtils

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.sample"
typeMapping = [
        (~/(?i)int/)                      : "long",
        (~/(?i)float|double|decimal|real/): "double",
        (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
        (~/(?i)date/)                     : "java.sql.Date",
        (~/(?i)time/)                     : "java.sql.Time",
        (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    //自动查找命名空间
    packageName = findPackageName(dir)
    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    //写入mapper文件
    new File(dir, className + "Mapper.java").withPrintWriter { out -> generate(out, className, fields, table.getName(), dir) }

    //写入xml文件
    def xmlDir = getModelXmlDir(dir)
    if(xmlDir != null) {
        new File(xmlDir, className + "Mapper.xml").withPrintWriter { out -> generateXml(out, className, fields, table.getName(), dir) }
    }
}

def generate(out, className, fields, tableName, dir) {
    def packageName = findPackageName(dir)
    def domainPacageName = findDomainPackageName(dir)
    if(packageName != "") out.println("package ${packageName};\n")
    out.println(
            "\n" +
            "import ${domainPacageName}.${className};\n" +
            "import com.baomidou.mybatisplus.core.mapper.BaseMapper;\n" +
            "import org.apache.ibatis.annotations.Mapper;\n\n" +
            "@Mapper\n" +
            "public interface ${className}Mapper extends BaseMapper<${className}>{\n" +
            "}")
}

def generateXml(out, className, fields, tableName, dir) {
    def packageName = findPackageName(dir)
    if(packageName == null) {
        packageName = "test"
    }

    out.println "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
    out.println "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">"
    out.println "<mapper namespace=\"${packageName}.${className}Mapper\">"
    out.println "   <resultMap type=\"${className}\" id=\"${className}Result\">"
    fields.each() {
        if (it.annos != "") out.println "  ${it.annos}"
        out.println "       <result property=\"${it.name}\"    column=\"${it.colName}\"    />"
    }
    out.println "   </resultMap>"
    out.println ""
    out.println "</mapper>"

}

/**
 * 查找domain命名空间
 *
 * @param dir
 */
def findDomainPackageName(dir) {
    return findPackageName(new File(dir.getParent() + "/domain"))
}


def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        def comment = "";
        if(col.getComment() != null) {
        }
        fields += [[
                           name : javaName(col.getName(), false),
                           colName: col.getName(),
                           type : typeStr,
                           comment: comment,
                           annos: ""]]
    }
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

/**
 * 获取模型packagename
 */
def getModelXmlDir(File dir) {
    if(dir.isDirectory()) {
        File mapperDir = null
        for (int i=0; i<10; i++) {
            dir = new File(dir.getParent());
            //检查该目录下是否存在资源目录
            for(File f in dir.listFiles()) {
                //资源目录处理
                if(f.isDirectory() && f.getName().equals("resources")) {
                    //找到了资源目录
                    //检查创建 mapper目录
                    for (File tmp in f.listFiles()) {
                        if(tmp.getName().equals("mapper")) {
                            mapperDir = tmp
                        }
                    }
                    //如果目录不存在则创建目录
                    if(mapperDir == null) {
                        mapperDir = new File(f.getAbsolutePath() + "/mapper")
                        mapperDir.mkdir();
                    }
                    break
                } else {
                    continue
                }
            }
            if(mapperDir != null) break;
        }
        return mapperDir;
    }
    return null
}

/**
 * 查找指定目录现有的命名空间
 *
 * @param dir
 * @return
 */
def findPackageName(dir) {
    if(dir != null && dir.isDirectory()) {
        File[] files = dir.listFiles();
        if(files != null && files.length>0) {
            for (File item:files) {
                if(item.isFile()) {
                    List<String> lines = Files.readLines(item, StandardCharsets.UTF_8);
                    //查找命名空间
                    for (String line: lines) {
                        line = line.trim();
                        if(line.startsWith("package")) {
                            line = line.split(" ")[1];
                            line = line.replace(";", "")
                            line = line.trim();
                            return line;
                        }
                    }
                }
            }
        }
    }
    return ""
}